<template>
  <div>
    <!-- 面包屑 -->
    <bread-crumb :names="['首页', '权限管理', '角色列表']"></bread-crumb>
    <h2>此页面为开发人员测试页,您可不予理会</h2>
    <!-- 卡片 -->
    <el-card class="box-card" shadow="hover">
      <add-role :showaddtRoleDialog.sync="showaddtRoleDialogs"></add-role>
      <el-table :data="rolesList" border style="width: 100%">
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-row
              v-for="(item, index) in row.children"
              :key="index"
              :class="[
                'row-bottom',
                index == 0 ? 'row-top' : '',
                'el-row-one',
                'vcenter',
              ]"
            >
              <!-- 绑定点击删除事件 -->
              <el-col :span="4"
                ><el-tag closable @close="deleteRights(row, item.id)">{{
                  item.authName
                }}</el-tag
                ><i class="el-icon-arrow-right"></i
              ></el-col>
              <el-col :span="20">
                <el-row
                  v-for="(item, index) in item.children"
                  :key="item.id"
                  :class="[index == 0 ? '' : 'row-top', 'vcenter']"
                >
                  <el-col :span="6">
                    <!-- 绑定点击删除事件 -->
                    <el-tag
                      type="success"
                      closable
                      @close="deleteRights(row, item.id)"
                      >{{ item.authName }}</el-tag
                    ><i class="el-icon-arrow-right"></i
                  ></el-col>
                  <el-col :span="18">
                    <!-- 绑定点击删除事件 -->
                    <el-tag
                      type="warning"
                      v-for="item in item.children"
                      :key="item.id"
                      closable
                      @close="deleteRights(row, item.id)"
                      >{{ item.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <!-- 编辑角色 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRoleInfo(row)"
              >编辑</el-button
            >
            <!-- 删除角色 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRole(row)"
              >删除</el-button
            >
            <!-- 分配权限 -->
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="displaySettingRoleRights(row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 编辑对话框 -->
    <el-dialog title="编辑用户" :visible.sync="showEditRoleDialog" width="50%">
      <el-form
        :model="roleInfo"
        label-width="80px"
        ref="roleEditForm"
        :rules="editrules"
      >
        <el-form-item prop="roleName" label="角色名称">
          <el-input
            v-model="roleInfo.roleName"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="roleDesc" label="角色描述">
          <el-input
            v-model="roleInfo.roleDesc"
            placeholder="请输入该角色的描述(选填)"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 权限管理对话框 -->
    <el-dialog title="权限管理" :visible.sync="showSetRightsDialig" @close='resetDefaultRightsList'>
      <el-tree
      ref='setRights'
  :data="rightsList"
  show-checkbox
  default-expand-all
  node-key="id"
  :default-checked-keys="defaultCheckedKeys"
  :props="defaultProps">
</el-tree>
<template #footer>
     <span class="dialog-footer">
        <el-button @click=" showSetRightsDialig=false">取 消</el-button>
        <el-button type="primary" @click='allotRights'>确 定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import BreadCrumb from "common/BreadCrumb";
import {
  getRolesList,
  editRole,
  deleteRoleDelete,
  deleRoleRightsDelete,
  getRightsListTree,
   allotRoleRights
} from "network/axios";
import { getAllLeafs } from 'utils/recursion'
import AddRole from "./roleChild/AddRole";
export default {
  name: "Role",
  components: { BreadCrumb, AddRole },
  data() {
    return {
      rolesList: [],
      showEditRoleDialog: false,
      roleInfo: {
        roleName: "",
        roleDesc: "",
        roleId: 0,
      },
      editrules: {
        roleName: [
          { required: true, message: "角色名不能为空", trigger: "blur" },
        ],
      },
      //添加角色对话框的显示与隐藏
      showaddtRoleDialogs: false,
      //分配权限的对话框的显示与隐藏
      showSetRightsDialig:false,
      //每个用户的拥有的权限列表
      rightsList:[],
      defaultProps:{
        label:'authName',
        children:'children'
      },
      //分配权限对话框默认选中的节点
      defaultCheckedKeys:[],
      //当前角色的id
      roleId:0
    };
  },
  created() {
    getRolesList().then((res) => {
      if (res.data.meta.status != 200) {
        return this.$message.error("获取角色信息失败");
      }
      this.rolesList = res.data.data;
    });
  },
  methods: {
    editRoleInfo(row) {
      this.showEditRoleDialog = true;
      this.roleInfo.roleName = row.roleName;
      this.roleInfo.roleDesc = row.roleDesc;
      this.roleInfo.roleId = row.id;
    },
    // 点击对话框中的提交按钮,发送网络请求根据状态码判断是否修改角色信息成功
    submitEdit() {
      this.$refs.roleEditForm.validate((flag) => {
        if (!flag) return;
        editRole(this.roleInfo)
          .then((res) => {
            if (res.data.meta.status != 200) {
              return this.$message.error("修改角色信息失败");
            }
            this.$message.success("修改角色信息成功");
            //   修改角色信息成功后重新发送网络请求,重新渲染页面
            getRolesList().then((res) => {
              if (res.data.meta.status != 200) {
                return this.$message.error("获取角色信息失败");
              }
              this.rolesList = res.data.data;
            });
          })
          .catch((err) => {
            this.$message.error("服务器忙,请稍后重试");
          });
        this.showEditRoleDialog = false;
      });
    },
    cancelEdit() {
      this.showEditRoleDialog = false;
      this.$message("您取消了用户编辑");
    },
    //添加角色
    addRole() {
      this.showaddtRoleDialogs = true;
    },
    //删除角色
    deleteRole(row) {
      this.$confirm("删除之后不可恢复,确定要删除该角色吗?", "确认信息", {
        confirmButtonText: "确认删除",
        cancelButtonText: "点错了",
      })
        .then(() => {
          deleteRoleDelete(row.id).then((res) => {
            if (res.data.meta.status != 200)
              return this.$message.error("删除失败");
            this.$message.success("删除成功");
            this.$router.push("/home/role");
          });
        })
        .catch(() => {
          this.$message("您取消了删除操作");
        });
    },
    //删除指定角色的指定权限
    deleteRights(role, rightsId) {
      this.$confirm("删除之后不可恢复,确定要此权限吗?", "确认信息", {
        confirmButtonText: "确认删除",
        cancelButtonText: "点错了",
      })
        .then(() => {
          deleRoleRightsDelete(role.id, rightsId).then((res) => {
            console.log(res);
            if (res.data.meta.status != 200)
              return this.$message.error("删除部分权限失败s");
            this.$message.success("删除权限成功");
            role.children = res.data.data;
          });
        })
        .catch(() => {
          this.$message("您取消了删除操作");
        });
    },
    //显示分配角色权限的对话框
    displaySettingRoleRights(role){
        this.roleId=role.id
            this.showSetRightsDialig=true
            console.log(role.children);
         getAllLeafs(role.children,this.defaultCheckedKeys)
          console.log(this.defaultCheckedKeys);
            getRightsListTree().then(res=>{
              this.rightsList=res.data.data
            })

    },
    //点击关闭对话框后应该把默认的值清空
    resetDefaultRightsList(){
      this.defaultCheckedKeys=[]
    },
    // 点击确定分配权限
    allotRights(){
            const rightsKeys=[]
            const halfkeys=this.$refs.setRights.getHalfCheckedKeys()
            const leafsKeys=this.$refs.setRights.getCheckedKeys()
            rightsKeys.push(...halfkeys,...leafsKeys)
            let rights=rightsKeys.join(',')
             this.showSetRightsDialig=false
            allotRoleRights(this.roleId,rights).then(res=>{
              if(res.data.meta.status!=200)
              return this.$message.error('更新失败')
              this.$message.success('更新成功')
               this.$router.push("/home/role");
            }).catch(err=>{
              this.$message.error('更新失败,服务器忙,请稍后再试')
            })
           


    }
  },
};
</script>

<style lang='less' scoped>
.el-table {
  margin-top: 20px;
  font-size: 12px;
}
.el-tag {
  margin: 10px;
}
.row-top {
  border-top: 1px solid #eee;
}
.row-bottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>